#include "StompedReality/Core/MessageSystem/Message.h"
#include "StompedReality/Core/MessageSystem/MessageTypes.h"
#include "StompedReality/LayerSystem.h"
namespace StompedReality
{
namespace Graphics
{
LayerSystem::LayerSystem( ) :
  StompedReality::Core::DataBuffer ( ( 12 * 2 ) * 8 ),
  StompedReality::Core::MessageHandler( )
{
  // init base values
  for ( int i = 0; i < 8; ++i )
  {
    this->SetTranslation ( i, StompedReality::Math::Vector2 ( 0, 0 ) );
    this->SetTranslationSpeed ( i, StompedReality::Math::Vector2 ( 1, 1 ) );
  }
}

LayerSystem::~LayerSystem( )
{
}

const StompedReality::Math::Vector2 LayerSystem::GetTranslation ( int layer )
{
  return this->GetValue<StompedReality::Math::Vector2> ( 24 * layer );
}

void LayerSystem::SetTranslation ( int layer,
                                   const StompedReality::Math::Vector2 transform )
{
  this->SetValue<StompedReality::Math::Vector2> ( 24 * layer, transform );
}

const StompedReality::Math::Vector2 LayerSystem::GetTranslationSpeed ( int layer )
{
  return this->GetValue<StompedReality::Math::Vector2> ( 24 * layer + 12 );
}

void LayerSystem::SetTranslationSpeed ( int layer,
                                        const StompedReality::Math::Vector2 speed )
{
  this->SetValue<StompedReality::Math::Vector2> ( 24 * layer + 12, speed );
}

bool LayerSystem::ProcessMessage ( StompedReality::Core::Message* msg )
{
  if ( StompedReality::Core::CAMERA_MOVEMENT == msg->GetMessageType( ) )
  {
    // get camera movement & layer
    const StompedReality::Math::Vector2 cameraMovement =
      msg->GetData<StompedReality::Math::Vector2> ( 0 );
    int layer = msg->GetData<int> ( 12 );

    // single layer
    if ( layer != -1 )
    {
      this->TranslateLayer ( layer, cameraMovement );
      return false;
    }

    // all layers
    for ( int i = 0; i < 8; ++i )
    {
      this->TranslateLayer ( i, cameraMovement );
    }
  }
  return false;
}

void LayerSystem::TranslateLayer ( int layer,
                                   const StompedReality::Math::Vector2 translation )
{
  // get camera movement speed and current translation
  StompedReality::Math::Vector2 pos = this->GetTranslation ( layer );
  StompedReality::Math::Vector2 speed = this->GetTranslationSpeed ( layer );

  // scale camera movement
  speed.Scale ( translation );

  // update and save translation
  pos += speed;
  this->SetTranslation ( layer, pos );
}

bool LayerSystem::ParseJSON ( Json::Value& root )
{
  return true;
}

bool LayerSystem::WriteJSON ( Json::Value& root )
{
  return true;
}

}
}
